package com.framework.mybatis.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fhs.core.trans.anno.TransMethodResult;
import com.framework.mybatis.entity.BaseEntity;
import com.framework.mybatis.service.BaseService;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;


public abstract class BaseServiceImpl<T extends BaseEntity> implements BaseService<T> {
    @Autowired(required = false)
    private BaseMapper<T> mapper;

    @TransMethodResult
    @Override
    public List<T> list(Wrapper<T> wrapper) {
        return mapper.selectList(wrapper);
    }

    @TransMethodResult
    @Override
    public IPage<T> list(Integer pageNum, Integer pageSize, Wrapper<T> wrapper) {
        IPage<T> page = mapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
        return page;
    }

    @Override
    public Integer save(T entity) {
        return mapper.insert(entity);
    }

    @Override
    public Integer update(T entity) {
        return mapper.updateById(entity);
    }

    @Override
    public Integer update(T entity, Wrapper<T> wrapper) {
        return mapper.update(entity, wrapper);
    }

    @Override
    public long count() {
        return mapper.selectCount(null);
    }

    @Override
    public long count(Wrapper<T> wrapper) {
        return mapper.selectCount(wrapper);
    }

    @TransMethodResult
    @Override
    public T first(Wrapper<T> wrapper) {
        val list = list(wrapper);
        if (list.size() == 0) {
            return null;
        }
        return list.get(0);
    }

    @TransMethodResult
    @Override
    public T getById(Long id) {
        return mapper.selectById(id);
    }

    @Override
    public Integer delete(Long id) {
        return mapper.deleteById(id);
    }

    @Override
    public Integer delete(Wrapper<T> wrapper) {
        return mapper.delete(wrapper);
    }

    @Override
    public Integer remove(T entity) {
        entity.setDeleteState(true);
        return update(entity);
    }


}
